package com.xyh.transaction.service.imp;

import com.github.pagehelper.PageInfo;
import com.xyh.transaction.common.Constant;
import com.xyh.transaction.common.Current;
import com.xyh.transaction.common.ImageType;
import com.xyh.transaction.entity.Image;
import com.xyh.transaction.entity.dto.RotateDto;
import com.xyh.transaction.entity.dto.user.ArrDto;
import com.xyh.transaction.entity.vo.RotateVo;
import com.xyh.transaction.mapper.ImageMapper;
import com.xyh.transaction.service.ImageService;
import com.xyh.transaction.utils.ImageUtils;
import com.xyh.transaction.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageMapper imageMapper;

    @Autowired
    private ImageUtils imageUtils;


    @Override
    public PageInfo<RotateVo> getRotateList(RotateDto bannerDto) {
        ArrayList<RotateVo> bannerVos = new ArrayList<>();

        List<Image> imageList = imageMapper.findByImageType(ImageType.BANNER);

        if (imageList.isEmpty()) {
            RotateVo bannerVo = new RotateVo();
            bannerVo.setId(15);
            bannerVo.setImgUrl(Constant.DEFAULT_BANNER);

            RotateVo bannerVo1 = new RotateVo();
            bannerVo1.setId(16);
            bannerVo1.setImgUrl(Constant.DEFAULT_BANNER);
            bannerVos.add(bannerVo);
            bannerVos.add(bannerVo1);
        } else {
            bannerVos.addAll(imageList.stream().map(image -> {
                RotateVo bannerVo = new RotateVo();
                bannerVo.setId(image.getId());
                bannerVo.setImgUrl(imageUtils.buildImageUrl(image.getUrl()));
                bannerVo.setAlt(image.getAltText());
                return bannerVo;
            }).collect(Collectors.toList()));
        }

        return PageUtil.paginateList(bannerVos, bannerDto.getPageNum(), bannerDto.getPageSize());
    }

    @Override
    public void addImage(RotateDto bannerDto) {
        Integer userId = Current.getCurrentUser().getUser().getId();
        Image image = new Image();
        image.setImageType(ImageType.BANNER);
        image.setUrl(ImageUtils.getFileNameFromUrl(bannerDto.getImgUrl()));
        image.setCreateBy(userId);
        image.setUpdateBy(userId);
        image.setCreateTime(LocalDateTime.now());
        image.setUpdateTime(LocalDateTime.now());
        imageMapper.insert(image);
    }

    @Override
    public void updateById(Image image) {
        imageMapper.update(image);
    }

    @Override
    public void deleteById(ArrDto arrDto) {
        imageMapper.deleteBatchByIds(Arrays.stream(arrDto.getId()).collect(Collectors.toList()));
    }
}
